package com.example.freemaker.freemaker.com.example.freemaker.freemaker.handler;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Map;

/**
 * @Auther: desk-----xuzhiliang
 * @Date: 2019/8/9 15:12
 * @Description:
 */
@Service("freeMakerTamplter")
public class FreeMakerTamplter {

    /**
     * 通过路径 和文件名称后去魔板
     *
     * @param templateFilePath
     * @param templateFileName
     * @return
     */
    public  Template getTemplate(String templateFilePath, String templateFileName) {
        try {
            Configuration cfg = new Configuration();
            cfg.setClassicCompatible(true);

            TemplateLoader templateLoader = new FileTemplateLoader(new File(
                    templateFilePath));
            cfg.setTemplateLoader(templateLoader);
            return cfg.getTemplate(templateFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * @param templateFilePath 加载的模板路劲
     * @param templateFileName 加载的模板文件名
     * @param replaceData
     * @param outFile          生成指定文件
     * @return 文件名
     */
    public  Writer freemarkToHtml(String templateFilePath, String templateFileName, Map<String, Object> replaceData,
                                        String outFile) {

        Writer out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(outFile), "UTF-8"));
            Template temp = getTemplate(templateFilePath, templateFileName);
            temp.setOutputEncoding("UTF-8");
            //执行翻译转化
            temp.process(replaceData, out);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return out;
    }
}

